//
// Created by 崔世强 on 2018/1/8.
// Copyright (c) 2018 Facebook. All rights reserved.
//

import Foundation

class TimeUtil {
    static let instance: TimeUtil = {
        return TimeUtil()
    }()
    
    func isGreatThan(a:TimeInterval,b:TimeInterval,difference: Int) -> Bool {
        return Int(a-b) > difference
    }
    
    lazy var formatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
        return formatter
    }()
    
    func string(_ date: Date) -> String{
        return formatter.string(from: date)
    }
    
    func date(_ str:String) -> Date{
        return formatter.date(from: str)!
    }
    
    func string(_ date:Date,formatterStr:String) -> String{
        let formatter = DateFormatter()
        formatter.dateFormat = formatterStr
        return formatter.string(from: date)
    }
    
    func calOfDay(from:Date,to:Date,ge:Int) -> Bool {
        let gregorian = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
        var result = gregorian!.components(.day, from: from, to: to, options: NSCalendar.Options(rawValue: 0))
        return (result.day ?? 0) >= ge
    }
    
    
    func chatTimeStr(_ time:TimeInterval) -> String {
        
        // 消息时间
        let date = Date(timeIntervalSince1970: time)
        
        let calendar: Calendar = Calendar(identifier: .gregorian)
        var comps = calendar.dateComponents([.year,.month,.day, .weekday, .hour, .minute,.second], from: date)
        // 当前时间
        let now = calendar.dateComponents([.year,.month,.day, .weekday, .hour, .minute,.second], from: Date())
        
        // 相差年份
        let year = now.year! - comps.year!
        // 相差月数
        let month = now.month! - comps.month!
        // 相差天数
        let day = now.day! - comps.day!
        // 相差小时
        let hour = now.hour! - comps.hour!
        // 相差分钟
        let minute = now.minute! - comps.minute!
        // 相差秒数
        let second = now.second! - comps.second!
        
        if year != 0 {
            return String(format: "%d年%d月%d日 %d:%02d", comps.year!, comps.month!, comps.day!, comps.hour!, comps.minute!)
        } else if year == 0 {
            if month > 0 || day > 2 {
                return String(format: "%d月%d日 %d:%02d", comps.month!, comps.day!, comps.hour!, comps.minute!)
            }else if day == 2 {
                return String(format: "前天 %d:%d", comps.hour!, comps.minute!)
            } else if day == 1 {
                return String(format: "昨天 %d:%d", comps.hour!, comps.minute!)
            } else if hour > 0 {
                return String(format: "%d:%02d",comps.hour!, comps.minute!)
            } else if minute > 0 {
                return String(format: "%d分钟前",minute)
            } else if second > 3 {
                return String(format: "%d秒前",second)
            } else  {
                return String(format: "刚刚")
            }
        }
        return ""
    }
}
